package com.book.iphone;

import com.book.book.domain.UsersDO;
import com.book.book.service.BooklogService;
import com.book.book.service.UsersService;
import com.book.iphone.domain.WeiXin;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by siyuan on 2018/2/4.
 */
@Controller
@RequestMapping("/iphone")
public class IphoneLoginController {

    @Value("${book.redirect}")
    private String redirect;
    @Autowired
    UsersService usersService;

    @Autowired
    private BooklogService booklogService;

    /***
     * 用户手机获取微信
     * 头像 昵称
     *
     * @return
     */
    @RequestMapping("/login")
    public String iphoneLogion(HttpServletRequest request, Model model) {
        //假数据开始
        UsersDO usersDO=new UsersDO();
        usersDO.setUserId("o11iD1NL37FWYY5IfPv85NE5YYIE");
        usersDO.setOpenId("o11iD1NL37FWYY5IfPv85NE5YYIE");
        usersDO.setId(17);
        usersDO.setPhone("13137697840");
        usersDO.setAddress("中国河南周口");
        usersDO.setIntegral(100);
        usersDO.setContribution(0);
        usersDO.setBorrowNum(1);
        usersDO.setIsBlack(0);
        usersDO.setReadAge(1);
        usersDO.setSex(1);
        usersDO.setMotto("哈哈哈");
        usersDO.setImages("http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLSod7M8st4d6LaJ4eL1DAJuy2OueaZm3vvoBwKcvu2amjgCcmTgBvw7kmVBaO9TTQxia6N65FPTDg/132");
        usersDO.setNickName("张宏");
        usersDO.setBirthday(new Date());
        request.getSession().setAttribute("userInfo",usersDO);
        //UsersDO usersDO1= (UsersDO) request.getSession(false).getAttribute("userInfo");
        model.addAttribute("userinfo",usersDO);
        /**
         * 登录后进行消息通知
         */
//        String holderId = "o11iD1ASoDBKNAaWyO2p7_fcxzNU";     // request.getParameter("userId");
//        List<BooklogDO> booklogDOList = booklogService.selectCallBackBooks(holderId);
//        for (BooklogDO b:booklogDOList) {
//            if (Integer.parseInt(b.getRedundance1()) > 3) {
//                booklogDOList.remove(b);
//            }
//        }
//        // 快到期的图书信息
//        model.addAttribute("booklogDOList",booklogDOList);
//        System.out.println(booklogDOList);

        return "book/phone/main/person";
        //假数据结束

//        //发布环境
//        String weixinInfo = request.getSession()
//                .getAttribute("userInfo") == null ? "" : request.getSession().getAttribute("userInfo").toString();
//        System.out.println(redirect);
//        if (weixinInfo.equals("")) {
//            String url = "http://shop.maliangss.com/addons/wx_agency/request_info.php?call_back=" + redirect;
//            return "redirect:" + url + "auth";
//        } else {
//            // 放入redis
//            // 跳转到个人中心
//            return "redirect:" + redirect + "user";
//        }

    }

    @RequestMapping("/auth")
    public String weixinAuth(HttpServletRequest request, HttpServletResponse response, Model model) {
        String userinfo = request.getParameter("info") == null ? "" : request.getParameter("info");
        if (!userinfo.isEmpty()) {
            try {
                Gson gson = new Gson();
                //JSONObject json = new JSONObject(userinfo);
                WeiXin weiXin = gson.fromJson(userinfo, WeiXin.class);
//                String openid = weiXin.getOpenid();
                UsersDO users = usersService.getopenid(weiXin.getOpenid());
                String errcode = weiXin.getErrcode();
                if (errcode == "40001") {
                    return "book/phone/error";
                }

                //先判断数据库的用户是否存在
                // 存在返回数据
                if (users == null) {
                    //插入用户数据信息
                    UsersDO usersDO = new UsersDO();
                    String city = weiXin.getCity();
                    String contry = weiXin.getCountry();
                    usersDO.setOpenId(weiXin.getOpenid());
                    String province = weiXin.getProvince();
                    usersDO.setAddress(contry + province + city);
                    usersDO.setImages(weiXin.getHeadimgurl());
                    usersDO.setNickName(weiXin.getNickname());
                    usersDO.setUserId(weiXin.getOpenid());
                    usersDO.setMotto("您还没有个性签名....");
                    usersDO.setSex(weiXin.getSex());
                    usersDO.setBirthday(new Date());
                    //   usersDO.setUserId();
                    weiXin.setCode(200);
                    weiXin.setMsg("congratulation");
                    usersService.save(usersDO);
                    request.getSession().setAttribute("userInfo", weiXin);
                    model.addAttribute("userinfo", weiXin);
                    //  return "redirect:"+redirect+"user";
                    return "book/phone/main/person";
                }
                if (users.getOpenId().equals(weiXin.getOpenid())) {
                    request.getSession().setAttribute("userInfo", users);
                    model.addAttribute("userinfo", users);
                    //  return "redirect:"+redirect+"user";
                    return "book/phone/main/person";
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        } else {
            new WeiXin(500, "授权失败！");
            request.getSession().setAttribute("userInfo", userinfo);

        }
        return "redirect:" + redirect + "login";

    }

}